<template>
  <div class="userLoginView">
    <h2 style="margin-bottom: 20px">用户登录</h2>
    <a-form
      style="max-width: 480px; margin: 0 auto"
      label-align="left"
      auto-label-width
      :model="form"
      @submit="handleSubmit"
    >
      <a-form-item
        field="userAccount"
        :rules="[
          { required: true, message: '账号必填' },
          { minLength: 3, message: '账号不少于3位' },
        ]"
        :validate-trigger="['change', 'input', 'blur']"
        label="账号"
      >
        <a-input v-model="form.userAccount" placeholder="请输入你的账号" />
      </a-form-item>
      <a-form-item
        :rules="[
          { required: true, message: '密码必填' },
          { minLength: 8, message: '密码不少于8位' },
        ]"
        :validate-trigger="['change', 'input', 'blur']"
        field="userPassword"
        label="密码"
      >
        <a-input-password
          v-model="form.userPassword"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="提交" style="width: 480px"
          >登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { UserControllerService, UserLoginRequest } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { Notification } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

/**
 * 表单信息
 */
const form = reactive({
  userAccount: "",
  userPassword: "",
} as UserLoginRequest);

/**
 * 提交表单
 */
const router = useRouter();
const store = useStore();
const handleSubmit = async () => {
  if (form.userAccount && form.userPassword) {
    const res = await UserControllerService.userLoginUsingPost(form);
    if (res.code === 0) {
      //设置登录状态
      await store.dispatch("user/getLoginUser");
      //登录成功，跳转页面
      router.push({
        path: "/",
        replace: true,
      });
    } else {
      message.error("登录失败", res.message);
    }
  } else {
    // message.error("请按要求填写表单！");
    Notification.error({
      title: "错误",
      content: "请按要求填写表单!",
    });
  }
};
</script>
